package com.origon.managedbeans;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.origon.entities.User;
import com.origon360.Services.UserService;
import com.origon360.utilities.NavigationHelper;
import com.origon360.utilities.SessionUtil;

@ManagedBean
@SessionScoped
public class LoginBean {
	
	@EJB
	private UserService userService;
	
	private final static Log LOGGER = LogFactory.getLog(LoginBean.class);
	
	
    private String userName;
	
	private String password;
	
	private User user;
		

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String login(){
		
		HttpServletRequest request = SessionUtil.getHttpServletRequest() ;
		
		try {
			
			if( request.getRemoteUser() == null){
				request.login(this.userName, this.password);
			}
			
				LOGGER.info(this.userName+ " has successfully logged in");
				
				this.user = userService.findUserByUserName(this.userName);
				
				
				LOGGER.info(this.userName+ " email is" +user.getActivationKey() +" registered on "+user.getRegistrationDate());
			return NavigationHelper.USERS_HOME_URI;
			
		} catch (ServletException e) {
			LOGGER.warn(userName+" "+password +" user authentication failed...", e);
			return null;
		}
		
		
	}
	
	public boolean isLoggedIn() {
		if(this.user == null)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	public String logout(){
		this.user = null;
			LOGGER.warn(userName+ " is being logged out...!");
			SessionUtil.getExternalContext().invalidateSession();
		return NavigationHelper.HOME_URI;
	}

}
